<template>
  <div class="issues-main" v-loading="loading" v-if="issuesData">
    <!-- 标题 -->
    <header class="issues-header">
      <div class="left-title">
        <div class="icon"></div>
        <h3>新建 Issue</h3>
        <div class="up_data_time" v-if="issuesData.created_at">
          <i class="iconfont iconshijian" />
          {{ issuesData.updated_at }}
          <p></p>
        </div>
      </div>
      <div class="right-title">
        <el-tooltip effect="dark" content="返回">
          <el-button @click.stop="handleBack" text>
            <svg class="action-icon" aria-hidden="true" width="18" height="18">
              <use xlink:href="#iconzuojiantou" fill="#409eff" />
            </svg>
          </el-button>
        </el-tooltip>
      </div>
    </header>
    <!-- 内容 -->
    <el-scrollbar>
      <div class="issues-content">
        <!-- 左侧内容 -->
        <div class="issues-wrap left">
          <el-form :model="issuesData" ref="ruleFormRef" status-icon :rules="rules">
            <el-form-item prop="title">
              <el-input
                size="large"
                maxlength="200"
                show-word-limit
                v-model="issuesData.title"
                placeholder="问题描述"
              />
            </el-form-item>
          </el-form>
          <!-- 富文本编辑器 -->
          <div class="issues-wrap editer">
            <IssuesEditor :issuesData="issuesData"></IssuesEditor>
            <el-button
              size="large"
              color="#6C52EA"
              type="warning"
              plain
              @click.stop="handleSave(pageId)"
              >{{ pageId ? '保存' : '创建' }}</el-button
            >
            <el-button size="large" class="cancel" @click="handleBack" plain>{{
              pageId ? '取消' : '返回'
            }}</el-button>
          </div>
        </div>
        <!-- 右侧表单 -->
        <div class="issues-wrap right">
          <div class="issues-wrap content">
            <RightForm
              @send-tagsDialog="handleDialog"
              :issuesData="issuesData"
              :defaultTopValue="defaultTopValue"
              ref="useGetData"
            >
            </RightForm>
          </div>
          <el-drawer
            v-model="tagsDialog"
            title="新建标签"
            direction="rtl"
            size="40%"
            :before-close="handleAddDialog"
          >
            <div>
              <AddTags @add-tagsDialog="handleAddDialog"></AddTags>
            </div>
          </el-drawer>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'

// import { newIProblemsData, getIProblemsList, editIProblemsData } from '@/apis/issues/issues-lists'
import { ElMessage, FormRules } from 'element-plus'
// import { newRecodeData } from '@/apis/issues/issues-record'
import { IProblems } from '@/views/problemCenter/config/problems'
import { editProblemsData, getProblemsList, newProblemsData } from '@/apis/system/problems'

import AddTags from './components/AddTags.vue'
import RightForm from './components/RightForm.vue'
import IssuesEditor from '../components/IssuesEditor.vue'
import Router from '@/router'

const defaultTopValue = ref('0')
const ruleFormRef = ref()
const rules = reactive<FormRules>({
  title: [{ required: true, message: '标题长度应为 1 ~ 200 个字符', trigger: 'blur' }]
})

/**
 *
 * @desc:获取登录用户信息
 */
const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

/**
 * 获取单条问题内容
 */
const issuesData = ref<IProblems>({
  id: 0,
  title: '',
  priority: '不指定',
  charge_id: [], // 负责人id
  content: '',
  top_id: 0,
  issues_tags: [],
  time_range: [],
  is_status: '待办的',
  user_name: getUserInfo.value.userName,
  like_id: [],
  user_id: getUserInfo.value.id,
  change_status_person_id: 0, //改变状态人的id
  updated_at: '',
  created_at: ''
})
const loading = ref(false)
const $router = useRouter()
const pageId = ref<number>(+$router.currentRoute.value.query.id!)
const getData = () => {
  loading.value = true
  let params = reactive({
    title: '',
    pageNum: 1,
    pageSize: 10
  })
  getProblemsList(params)
    .then((res) => {
      if (!res.rows) return
      res.rows.forEach((element: IProblems) => {
        element.created_at = new Date(
          +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
        )
          .toISOString()
          .replace(/T/g, ' ')
          .replace(/\.[\d]{3}Z/, '')
      })
      issuesData.value = res.rows[0]
      // issuesData.value = res.rows.filter((item: IProblems) => item.id === pageId.value)[0]
      //   findUserLike.value = issuesData.value?.like_id.find((item: IlikeData) => {
      //     return item.uid === getUserInfo.value.id
      //   })
      //   countLikeNum.value = issuesData.value?.like_id.filter((item) => {
      //     return item.status === 1
      //   })
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      loading.value = false
    })
}

if (!!pageId.value) {
  getData()
}

/**
 * @desc: 增加标签
 */
const tagsDialog = ref(false)
const handleDialog = () => {
  tagsDialog.value = true
}

/**
 * @desc: 增加标签抽屉取消
 */
const useGetData = ref<InstanceType<typeof RightForm>>()
const handleAddDialog = () => {
  useGetData.value?.getData()
  tagsDialog.value = false
}

/**
 * @desc: 创建问题
 */
const createData = () => {
  newProblemsData(issuesData.value)
    .then((res) => {
      if (!res) return
      handleBack()
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * @desc: 修改问题
 */
const editData = (id: number) => {
  issuesData.value._id = id
  editProblemsData(issuesData.value)
    .then((res) => {
      if (!res) return
      // let params = {
      //   user_id: getUserInfo.value.id,
      //   issues_id: res.data.id,
      //   status: res.data.status
      // }
      // 记录操作日志
      // newRecodeData(params)
      handleBack()
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * @desc: 保存
 */
const handleSave = (id: number) => {
  ruleFormRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true
      if (id) {
        editData(id)
      } else {
        createData()
      }
    }
  })
}

/**
 * @desc: 后退
 */
const handleBack = () => {
  Router.back()
}
</script>

<style lang="less" scoped>
@color: #fdf6ec;
.issues-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 10px 0;
  .left-title {
    display: flex;
    align-items: center;
    padding-bottom: 20px;
    .icon {
      height: 26px;
      width: 6px;
      box-sizing: border-box;
      background: #409eff;
      border-radius: 3px;
      margin-right: 16px;
    }
    .up_data_time {
      margin-left: 24px;
      transform: translateY(2px);
      color: #999;
    }
  }
  .right-title {
    display: flex;
    justify-content: flex-end;
    height: 26px;
    line-height: 26px;
    padding-bottom: 20px;
  }
}
.issues-main {
  display: flex;
  flex-direction: column;
  border-radius: 10px;
  padding-bottom: 10px;
  height: 100%;
  background: #fff;
  .issues-content {
    display: flex;
    .left {
      padding: 10px 10px;
      width: 70%;
    }
    .right {
      flex: 1;
      padding: 10px 10px;
      .content {
        margin-left: 10px;
      }
    }
    .el-button--large {
      margin-top: 20px;
    }
  }
}
</style>
